package com.rtsapp.server.utils.logger;

import com.rtsapp.server.logger.Logger;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 日志记录线程
 * TODO 日志记录线程可以复用
 */
public class LoggerThread implements Runnable{

    private static final Logger LOGGER =com.rtsapp.server.logger.LoggerFactory.getLogger(LoggerThread.class);

    private final LinkedBlockingQueue<byte[]> logs = new LinkedBlockingQueue();

    private final BinRollingLogger logger;

    private volatile boolean shutdown = false;

    public LoggerThread( BinRollingLogger logger ){
        this.logger = logger;
    }

    /**
     * 加入一条日志
     * @param log
     * @throws InterruptedException
     */
    public void appendLog( byte[] log )  {
        if( log == null || log.length < 1 ){
            return;
        }

        internalAppendLog(log);
    }


    private void internalAppendLog(byte[] log) {
        try {
            logs.put( log );
        } catch (InterruptedException e) {
            LOGGER.error( "追加日志时被中断", e);
        }
    }

    /**
     * 线程停止
     */
    public void shutdown(){
        this.shutdown = true;

        internalAppendLog( new byte[0] );
    }

    /**
     *
     */
    @Override
    public void run() {

        for(;;){

            try {

                if( shutdown ){
                    break;
                }

                byte[] log =   logs.take();

                if( log == null || log.length < 1 ){
                    continue;
                }

                logger.appendLog( log, 0, log.length );

            } catch (InterruptedException e) {
                LOGGER.error( "LoggerThread执行被中断", e );
            } catch( Throwable ex ){
                LOGGER.error(  "LoggerThread执行被中断", ex );
            }

        }

        LOGGER.info( "LoggerThread shutdown" );
    }
}
